//
//  QuickOpenCollectionViewController.m
//  HaiKangDemo
//
//  Created by 崔 on 2016/10/27.
//  Copyright © 2016年 崔. All rights reserved.
//

#import "QuickOpenCollectionViewController.h"
#import "OpeningCollectionViewCell.h"
#import "LGControllerManager.h"
#import "LGController.h"
#import "LGDoor.h"
#import "LoginWindow.h"

#import "AFURLSessionManager.h"
#import "AFHTTPSessionManager.h"
#import <SVProgressHUD.h>

#import "ALSHeader.h"

@interface QuickOpenViewController () <UICollectionViewDelegate,UICollectionViewDataSource,UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
//搜索 蒙板
@property (weak, nonatomic) UIButton *maskBtn;

@property (strong, nonatomic) NSMutableArray <NSMutableArray <LGDoor *>*>*doors;
@property (strong, nonatomic) NSMutableArray<NSString *> *sectionTitles;
@end

@implementation QuickOpenViewController

static NSString * const reuseIdentifier = @"Cell";

static NSString *cellID = @"OpeningCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpCollectionView];
    
    [self setUpSearchBar];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(als3DTouchWithNotification:) name:ALS3DTouchSearchNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(als3DTouchWithNotification:) name:ALS3DTouchCameraNotification object:nil];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(als3DTouchWithNotification:) name:LoginWindowDismissNotification object:nil];

}

BOOL threeTouchSearch = NO;

- (void)als3DTouchWithNotification:(NSNotification *)notification {

    if ([notification.name isEqualToString:ALS3DTouchSearchNotification]) threeTouchSearch = YES;
    
    if ([notification.name isEqualToString:ALS3DTouchCameraNotification]) threeTouchSearch = NO;
    
    if ([LoginWindow shareLoginWindw].hidden && threeTouchSearch) {
        [self.searchBar becomeFirstResponder];
        threeTouchSearch = NO;
    }
 
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //appear时刷新数据

    [self setupDoorsAndSectionTitles];
    [self.collectionView reloadData];
}

- (void)viewDidDisappear:(BOOL)animated {
    //disappear时 取消搜索
    [self searchBarCancelButtonClicked:self.searchBar];
}
//初始化searchBar
- (void)setUpSearchBar{
    
    self.searchBar.placeholder = @"搜索门 (点击门图标即可开门)";
    
    self.searchBar.delegate = self;
    
    [self.searchBar setTintColor:kColorFromRGB(0x3FEDEB)];
    
    UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
    searchField.textColor = [UIColor whiteColor];
}

//初始化collectionView

- (void)setUpCollectionView{

    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];

    
    UINib *nib = [UINib nibWithNibName:@"OpeningCollectionViewCell" bundle:nil];
    
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:cellID];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 2.每个cell的尺寸
    layout.itemSize = CGSizeMake(62, 80);
    // 3.设置cell之间的水平间距
    layout.minimumInteritemSpacing = 0.5;
    
    // 4.设置cell之间的垂直间距
    layout.minimumLineSpacing = 1;
    // 5.设置四周的内边距
    layout.sectionInset = UIEdgeInsetsMake(5, 0, 10, 0);
    
    self.collectionView.collectionViewLayout = layout;
    
    self.collectionView.dataSource = self;
    
    self.collectionView.delegate = self;


//    [self.collectionView registerClass:[] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerID"];
    
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return self.doors.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.doors[section].count;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    OpeningCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    LGDoor *door = self.doors[indexPath.section][indexPath.item];
    
    cell.doorName.text = door.doorName;

    
    if (door.attributedName) {
        cell.doorName.attributedText = door.attributedName;
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(kScreen_W, 25);
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.backgroundColor = [UIColor clearColor];
        
        UIView *highlightedView = [[UIView alloc]init];
        highlightedView.backgroundColor = kALSHightBlueColor;
        highlightedView.width = 4;
        highlightedView.height = header.height * 0.6;
        highlightedView.x = 10;
        highlightedView.y = (header.height - highlightedView.height ) / 2;
        highlightedView.layer.cornerRadius = 1;
        highlightedView.layer.masksToBounds = YES;
        
        UILabel *lable = [[UILabel alloc]init];
        lable.text = self.sectionTitles[indexPath.section];
        lable.font = [UIFont systemFontOfSize:15];
        lable.textColor = [UIColor whiteColor];
        [lable sizeToFit];
        lable.x = highlightedView.right + 5;
        lable.y = (header.height - lable.height) / 2;
        
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        button.frame = header.bounds;
//        [button setTitle:[NSString stringWithFormat:@"%ld", indexPath.section] forState:UIControlStateNormal];
//        [button addTarget:self action:sel_registerName("doOpen:") forControlEvents:UIControlEventTouchUpInside];
//        button.tag = 1000 + indexPath.section;
        for (UIView *view in header.subviews) {
            [view removeFromSuperview];
        } // 防止复用分区头
//        [header addSubview:button];
        [header addSubview:highlightedView];
        [header addSubview:lable];

        return header;
    } else {
        return nil;
    }
    
//    UICollectionReusableView *view = [[UICollectionReusableView alloc]init];
//    view.backgroundColor = [UIColor yellowColor];
//    return view;    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    LGDoor *door = self.doors[indexPath.section][indexPath.item];

    OpeningCollectionViewCell *cell = (OpeningCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    [cell.doorImage setHighlighted:YES];
    
    cell.doorName.textColor = kALSHightBlueColor;
    
    __weak typeof(self)weakSelf = self;
    
    [DCMI openDoor:door reply:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@-已打开",door.doorName]];
            
            //关闭提示框
            [weakSelf closeHint];
            
            //改变cell内部颜色
            [weakSelf changeCellInsideColor:cell];
        }else {
            
            [SVProgressHUD showErrorWithStatus:@"开门失败,请检查网络连接"];
            
            [weakSelf closeHint];
            
            [weakSelf changeCellInsideColor:cell];
            
        }
    }];
}


//关闭提示
- (void)closeHint{
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
            
        });
    });
   
    
}

//改变cell内部的颜色
- (void)changeCellInsideColor:(OpeningCollectionViewCell *)cell {
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
    cell.doorName.textColor = [UIColor whiteColor];
    
    [cell.doorImage setHighlighted:NO];
        
    });
    
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

}

#pragma mark <UISearchBarDelegate>

// UISearchBarDelegate定义的方法，用户单击取消按钮时激发该方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    self.maskBtn.hidden = YES;
    searchBar.text = nil;
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    [self setupDoorsAndSectionTitles];
    [self.collectionView reloadData];
}
// UISearchBarDelegate定义的方法，当搜索文本框内文本改变时激发该方法
- (void)searchBar:(UISearchBar *)searchBar
    textDidChange:(NSString *)searchText {
    
    if (searchText.length == 0) return;
    
    [DCMI searchDoorWithAndRecommend:searchText reply:^(NSArray<LGDoor *> * _Nullable resultArr, NSArray<LGDoor *> * _Nullable recommendArr) {
        
        self.doors = [NSMutableArray array];
        self.sectionTitles = [NSMutableArray array];
        if (resultArr.count != 0) {
            [self.doors addObject:[NSMutableArray arrayWithArray:resultArr]];
            [self.sectionTitles addObject:@"搜索结果"];
        }
        
        if (recommendArr.count != 0) {
            [self.doors addObject:[NSMutableArray arrayWithArray:recommendArr]];
            [self.sectionTitles addObject:@"推荐结果"];
        }
        
        [self.collectionView reloadData];
        
    }];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    //无搜索内容 取消搜索
    if (searchBar.text.length == 0) {
        [self searchBarCancelButtonClicked:searchBar];
        return;
    }
    
    //关闭键盘
    [searchBar resignFirstResponder];
    UIButton *cancelBtn = [searchBar valueForKey:@"cancelButton"];
    cancelBtn.enabled = YES;

    self.maskBtn.hidden = YES;
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    self.maskBtn.hidden = NO;
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}


- (void)searchBarResignFirstResponder {
    [self searchBarSearchButtonClicked:self.searchBar];
}

#pragma mark - UIScrollViewDelegate

#pragma mark - load

- (UIButton *)maskBtn {
    if (_maskBtn == nil) {
        UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];

        btn.frame = self.collectionView.frame;
        
        btn.backgroundColor = [UIColor colorWithWhite:0.6 alpha:0.3];
        btn.hidden = YES;
        [btn addTarget:self action:@selector(searchBarResignFirstResponder) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view addSubview:btn];
        _maskBtn = btn;
    }
    return _maskBtn;
}

- (void)setupDoorsAndSectionTitles {
    self.doors = [NSMutableArray array];
    self.sectionTitles = [NSMutableArray array];
    
    NSArray *usefulFrequencyOrderDoors = DCMI.usefulFrequencyOrderDoors;
    
    NSInteger favorite = -2;
    NSMutableArray *arr;
    for (LGDoor *door in usefulFrequencyOrderDoors) {
        if (favorite != door.favorite) {
            favorite = door.favorite;
            if (arr.count != 0) {
                [self.doors addObject:arr];
            }
            arr = [NSMutableArray array];
            
            switch (favorite) {
                case -1:
                    [self.sectionTitles addObject:@"不常用"];
                    break;
                case 0:
                    [self.sectionTitles addObject:@"默认"];

                    break;
                case 1:
                    [self.sectionTitles addObject:@"常用"];
                    break;
                default:
                    break;
            }
            
        }
        [arr addObject:door];
    }
    
    if (arr.count != 0) {
        [self.doors addObject:arr];
    }
    
}

#pragma mark - other

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end

///**是否处于搜索状态*/
//@property (nonatomic ,assign) BOOL isSearch;

////门禁数据
//@property (strong, nonatomic) NSArray<LGDoor *> *doorsArr;
//

///**搜索状态下的数据*/
//@property (nonatomic ,strong) NSMutableArray<LGDoor *> *searchData;
//

//- (void)filterBySubstring:(NSString*) subStr {
//
//    [DCMI searchDoorWithAndRecommend:subStr reply:^(NSArray<LGDoor *> * _Nullable resultArr, NSArray<LGDoor *> * _Nullable recommendArr) {
//
//        self.doors = [NSMutableArray array];
//        self.sectionTitles = [NSMutableArray array];
//        if (resultArr.count != 0) {
//            [self.doors addObject:[NSMutableArray arrayWithArray:resultArr]];
//            [self.sectionTitles addObject:@"搜索结果"];
//        }
//
//        if (recommendArr.count != 0) {
//            [self.doors addObject:[NSMutableArray arrayWithArray:recommendArr]];
//            [self.sectionTitles addObject:@"推荐结果"];
//        }
//
//        [self.collectionView reloadData];
//
//    }];
//    return;
//    [DCMI searchDoorWith:subStr reply:^(NSArray * _Nullable resultArr) {
//        if (resultArr.count != 0) {
//            self.searchData = [NSMutableArray arrayWithArray:resultArr];
//            self.isSearch = YES;
//
//            self.isSearch = NO;
////            self.doors = resultArr;
//            [self.collectionView reloadData];
//        }
//    }];
//
//    return;
//
//}


//    NSMutableString *str = [subStr mutableCopy];
//    CFStringTransform(( CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
//    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
//    NSString *outputPinyin = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
//    outputPinyin = [outputPinyin lowercaseStringWithLocale:[NSLocale currentLocale]];


//    self.searchData = [NSMutableArray array];
//
//    for (int i=0; i<self.doorsArr.count; i++) {
//        if ([self.doorsArr[i].pinyin containsString:outputPinyin]) {
//            [self.searchData addObject:self.doorsArr[i]];
//        }
//    }
//
//    self.isSearch = YES;
//    [self.collectionView reloadData];

/*
 //    NSMutableArray<NSString *> *titles = [NSMutableArray array];
 //    for (int i=0; i<self.searchData.count; i++) {
 //        [titles addObject:self.searchData[i].doorName];
 //    }
 //    [self.searchBar setScopeButtonTitles:titles];
 
 
 
 
 // 设置为搜索状态
 self.isSearch = YES;
 // 定义搜索谓词
 NSPredicate* pred = [NSPredicate predicateWithFormat:
 @"SELF CONTAINS[c] %@" , subStr];
 // 使用谓词过滤NSArray
 NSMutableArray *arr = [NSMutableArray array];
 for (int i=0; i<self.doorsArr.count; i++) {
 [arr addObject:self.doorsArr[i].doorName];
 }
 self.searchData = [self.doorsArr filteredArrayUsingPredicate:pred];
 
 // 让表格控件重新加载数据
 //    [self.collectionView reloadData];
 */

/*
 NSInteger port = [door.port integerValue];
 
 if (port == 0) {
 port = 80;
 }
 
 //获取通讯密码
 NSString *cPassWord = [[NSUserDefaults standardUserDefaults] objectForKey:ALSCommunicationPassWord];
 
 int cp = [cPassWord intValue];
 
 NSString *urlStr = [NSString stringWithFormat:@"http://%@:%ld/t,cgi?T%d,access_io,door,%lu,01",door.ip,(long)port,cp,(unsigned long)door.doorIndex];
 
 
 NSURL *url = [NSURL URLWithString:urlStr];
 
 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:1 timeoutInterval:2];
 
 
 [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
 
 //        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 
 dispatch_async(dispatch_get_main_queue(), ^{
 
 
 if (data){
 
 //                NSLog(@"%@",result);
 
 [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@-已打开",door.doorName]];
 
 //关闭提示框
 [weakSelf closeHint];
 
 //改变cell内部颜色
 [weakSelf changeCellInsideColor:cell];
 
 }
 
 if (error) {
 //                NSLog(@"%@",error);
 
 if (!error || ![error isEqual:@"ok"]) {
 
 
 [SVProgressHUD showErrorWithStatus:@"开门失败,请检查网络连接"];
 
 [weakSelf closeHint];
 
 [weakSelf changeCellInsideColor:cell];
 }
 
 }
 
 });
 
 
 }] resume];
 */


//- (LGControllerManager *)controllerManager {
//    if (_controllerManager == nil) {
//        _controllerManager = [LGControllerManager
//                              shareControllerManager];
//    }
//    return _controllerManager;
//}

//- (HanyuPinyinOutputFormat *)outputFormat {
//    if (_outputFormat == nil) {
//        _outputFormat = [[HanyuPinyinOutputFormat alloc] init];
//        [_outputFormat setToneType:ToneTypeWithoutTone];
//        [_outputFormat setVCharType:VCharTypeWithV];
//        [_outputFormat setCaseType:CaseTypeLowercase];
//    }
//    return _outputFormat;
//}
